package com.controller;

import net.sf.json.JSONObject;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

/**
 * @Program: exam
 * @ClassName: PicServletController
 * @Description: 文件上传
 * @Author: li
 */
@WebServlet("/PicServlet")
public class PicServletController extends HttpServlet {
    // 上传文件存储目录
    private static final String UPLOAD_DIRECTORY = "upload/images";
    private static final int MEMORY_THRESHOLD = 1024 * 1024 * 3;  // 3MB
    private static final int MAX_FILE_SIZE = 1024 * 1024 * 40;    // 40MB
    private static final int MAX_REQUEST_SIZE = 1024 * 1024 * 50; // 50MB

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) 
            throws ServletException, IOException {
        response.setContentType("application/json;charset=UTF-8");
        request.setCharacterEncoding("utf-8");
        response.setCharacterEncoding("utf-8");
        
        Map<String, Object> result = new HashMap<>();
        
        try {
            // 配置上传参数
            DiskFileItemFactory factory = new DiskFileItemFactory();
            // 设置内存临界值
            factory.setSizeThreshold(MEMORY_THRESHOLD);
            // 设置临时存储目录
            factory.setRepository(new File(System.getProperty("java.io.tmpdir")));

            ServletFileUpload upload = new ServletFileUpload(factory);
            // 设置最大文件上传值
            upload.setFileSizeMax(MAX_FILE_SIZE);
            // 设置最大请求值（包含文件和表单数据）
            upload.setSizeMax(MAX_REQUEST_SIZE);
            // 设置字符编码
            upload.setHeaderEncoding("UTF-8");

            // 确保目录存在
            String uploadPath = getServletContext().getRealPath("") + File.separator + UPLOAD_DIRECTORY;
            File uploadDir = new File(uploadPath);
            if (!uploadDir.exists()) {
                uploadDir.mkdirs();
            }

            // 解析请求的内容提取文件数据
            List<FileItem> formItems = upload.parseRequest(request);

            if (formItems != null && !formItems.isEmpty()) {
                for (FileItem item : formItems) {
                    // 处理不在表单中的字段
                    if (!item.isFormField()) {
                        String fileName = new File(item.getName()).getName();
                        if (fileName == null || fileName.isEmpty()) {
                            continue;
                        }

                        // 检查文件类型
                        String fileExtension = fileName.substring(fileName.lastIndexOf(".")).toLowerCase();
                        if (!fileExtension.matches("\\.(jpg|jpeg|png|gif)$")) {
                            result.put("code", 400);
                            result.put("msg", "只支持jpg、jpeg、png、gif格式的图片");
                            response.getWriter().write(JSONObject.fromObject(result).toString());
                            return;
                        }

                        // 生成新的文件名
                        String newFileName = UUID.randomUUID().toString() + fileExtension;
                        String filePath = uploadPath + File.separator + newFileName;
                        File storeFile = new File(filePath);

                        // 保存文件到硬盘
                        item.write(storeFile);

                        // 返回成功响应
                        result.put("code", 0);
                        result.put("msg", "上传成功");
                        result.put("data", new HashMap<String, String>() {{
                            put("url", "/" + UPLOAD_DIRECTORY + "/" + newFileName);
                        }});
                        break;
                    }
                }
            } else {
                result.put("code", 400);
                result.put("msg", "未找到上传的文件");
            }
        } catch (Exception e) {
            e.printStackTrace();
            result.put("code", 500);
            result.put("msg", "上传失败：" + e.getMessage());
        }
        
        response.getWriter().write(JSONObject.fromObject(result).toString());
    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) 
            throws ServletException, IOException {
        doPost(request, response);
    }
}
